package cn.wolfcode.trip.admin.controller;


import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("region")
public class RegionController {

    @Autowired
    private IRegionService regionService;

    @RequestMapping("list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){

        return "region/list";
    }

    @RequestMapping("getByParentId")
    @ResponseBody
    public List<Map> getByParentId(Long id){
        List<Region> list = regionService.getByParentId(id);
        //需要返回treeview指定的格式
        List<Map> treeList = new ArrayList<>();
        for (Region region:list){
            treeList.add(region.toTreeViewMap());
        }
        return treeList;
    }

    @RequestMapping("listChildRegion")
    @ResponseBody
    public List<Region> listChildRegion(Long id){

        return regionService.getByParentId(id);
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(Region region){
        JSONResult result = new JSONResult();
        try {
            if (region.getId()!=null){
                regionService.update(region);
            }else {
                regionService.save(region);
            }
        }catch (Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    @RequestMapping("updateState")
    @ResponseBody
    public JSONResult updateState(Integer state,Long id){
        JSONResult result = new JSONResult();
        try {
            regionService.updateState(state,id);
        }catch (Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    @RequestMapping("listAll")
    @ResponseBody
    public List<Region> listAll(){

        return regionService.listAll(null);
    }
}

